#!/usr/bin/env bash
set -Eeuo pipefail

# 一键“编译” Python：将 .py 编译为 .pyc 并放入 out/

BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUT_DIR="$BASE_DIR/out"
mkdir -p "$OUT_DIR"

PY=""
if command -v python3 >/dev/null 2>&1; then
  PY="python3"
elif command -v python >/dev/null 2>&1; then
  PY="python"
else
  echo "[python] 未找到 Python（python3/python）。请安装后重试。"
  exit 0
fi

echo "[python] 使用解释器: $PY"

# 逐个编译为 out/<name>.pyc，避免依赖 __pycache__ 与环境变量
"$PY" - <<'PY'
import os, py_compile
base = os.path.dirname(__file__)
out = os.path.join(base, 'out')
os.makedirs(out, exist_ok=True)
moved = 0
for name in os.listdir(base):
    if name.endswith('.py') and name != 'build.sh':
        src = os.path.join(base, name)
        dst = os.path.join(out, name[:-3] + '.pyc')
        try:
            py_compile.compile(src, cfile=dst, doraise=True)
            print(f"[python] 编译 {name} -> out/{os.path.basename(dst)}")
            moved += 1
        except Exception as e:
            print(f"[python] 编译失败 {name}: {e}")
print(f"[python] 完成。已将 {moved} 个 .pyc 放入 out/。")
PY
